package com.freejava.unittestrestfulapi.controller;

import com.freejava.unittestrestfulapi.entity.Toy;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class ToyController {
    // 创建线程安全的Map对象
    static Map<Long, Toy> toys = Collections.synchronizedMap(new HashMap<Long, Toy>());

    /**
     * 获取玩具列表
     *
     * @return
     */
    @GetMapping(value = "/toys")
    public List<Toy> getToyList() {
        List<Toy> toyLists = new ArrayList<Toy>(toys.values());
        return toyLists;
    }

    /**
     * 创建玩具
     *
     * @param toy
     * @return
     */
    @RequestMapping(value = "/toys", method = RequestMethod.POST)
    public String createToy(@ModelAttribute Toy toy) {
        toys.put(toy.getId(), toy);
        return "success";
    }

    /**
     * 通过id获取玩具
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/toys/{id}")
    public Toy getToy(@PathVariable Long id) {
        return toys.get(id);
    }

    /**
     * 更新玩具
     *
     * @param toy
     * @return @RequestBody
     */
    @PutMapping(value = "/toys")
    public String updateToy(Toy toy) {
//        Toy t = toys.get(toy.getId());
//        t.setDesc(toy.getDesc());
//        toys.put(toy.getId(), t);
        return "success";
    }

    /**
     * 根据id删除玩具
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/toys/{id}")
    public String deleteToy(@PathVariable Long id) {
        toys.remove(id);
        return "success";
    }

}